package com.kugoweb.shthon2011s.tlwatch.commons;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.content.Intent;
import android.net.Uri;

public class TweetUtils {

	public static final String CALLBACK_URL = "kamakura://kugoweb.com";
	private static final String KEY = "xxxxx";
	private static final String SECRET = "yyyyy";

	private static OAuthAuthorization sAuth = null;

	/**
	 * 認証用のIntentを返す
	 * 
	 * @return
	 * @throws TwitterException
	 */
	public static Intent getAuthIntent() throws TwitterException {
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		final OAuthAuthorization auth = getAuth();
		auth.setOAuthAccessToken(null);
		intent.setData(Uri.parse(getAuth().getOAuthRequestToken(CALLBACK_URL)
				.getAuthorizationURL()));
		return intent;
	}

	/**
	 * OAuthAuthorizationを返す
	 * 
	 * @return
	 */
	public static synchronized OAuthAuthorization getAuth() {
		if (sAuth == null) {
			final ConfigurationBuilder cb = new ConfigurationBuilder();
			cb.setOAuthConsumerKey(TweetUtils.KEY);
			cb.setOAuthConsumerSecret(TweetUtils.SECRET);
			sAuth = new OAuthAuthorization(cb.build());
		}
		return sAuth;
	}

	/**
	 * Twitterオブジェクトを返す
	 * 
	 * @param settingsData
	 * @return
	 */
	public static Twitter getTwitter(final SettingsData settingsData) {
		final ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setOAuthConsumerKey(TweetUtils.KEY);
		cb.setOAuthConsumerSecret(TweetUtils.SECRET);
		final String token = settingsData.getTwitterToken();
		final String secret = settingsData.getTwitterSecret();
		if (Utils.isEmpty(token) || Utils.isEmpty(secret)) {
			return null;
		} else {
			cb.setOAuthAccessToken(settingsData.getTwitterToken());
			cb.setOAuthAccessTokenSecret(settingsData.getTwitterSecret());
			final Configuration cfg = cb.build();
			final TwitterFactory tf = new TwitterFactory(cfg);
			return tf.getInstance();
		}
	}

}
